package com.ruoyi.web.controller.tcp;


import com.gg.reader.api.dal.GClient;
import com.gg.reader.api.dal.GServer;
import com.gg.reader.api.dal.HandlerGClientConnected;
import com.gg.reader.api.dal.HandlerTcpDisconnected;
import com.gg.reader.api.protocol.gx.MsgBaseStop;

/**
 * 处于客户端模式时，tcp连接不可用，若需要使用，请使用串口连接设置为服务器模式
 */
public class TcpServer {


//    public static void main(String[] args) {
//        GServer server = new GServer();
//        // TODO: 首先通过[读写器管理软件]设置设备为客户端模式 ip为上位机ip 端口为所要监听的端口
//        if (server.open(8160)) {
//            subscribeServerHandler(server);
//            System.out.println("开始监听");
//        } else {
//            System.out.println("监听失败");
//        }
//
//    }


    //订阅监听上报
    public static void subscribeServerHandler(GServer server) {
        server.onGClientConnected = new HandlerGClientConnected() {
            @Override
            public void log(GClient gClient, String serialNumber) {

                ReadEPCGpiInOutNewD01.subscribeHandler(gClient);
                System.out.println(gClient.getName() + "---监听成功");
                gClient.setSendHeartBeat(true);//开启心跳检测Tcp连接状态
                gClient.setPrint(true);
                subscribeTcpHandler(gClient);//订阅Tcp断连上报

                testStop(gClient);//测试监听成功的连接是否通信正常
            }
        };
    }

    //订阅TCP断开连接上报
    private static void subscribeTcpHandler(final GClient client) {
        client.onDisconnected = new HandlerTcpDisconnected() {
            @Override
            public void log(String s) {
                System.out.println("连接" + s + "已断开");
                client.close();//释放当前连接资源
            }
        };
    }

    private static void testStop(GClient client) {
        MsgBaseStop msg = new MsgBaseStop();
        client.sendSynMsg(msg);
        if (0x00 == msg.getRtCode()) {
            System.out.println("Stop success");
        } else {
            System.out.println(msg.getRtMsg());
        }
    }
}
